#include "../../ctlPassword.h"

namespace swui
{
	bool ctlPassword::create(ctlRoot* parent, ctlPoint pos, unsigned width, 
			const ctlText& lpszText, const ctlStyleEdit& style)
	{
		if(!ctlSingleEdit::create(parent, pos, width, lpszText, style))
			return false;
		std::lock_guard<decltype(_eventTrans)> gurad(
			_eventTrans.getControlEventTrans(parent));
		_control_virtual_class_end = this;
		_controlType = ctlControlType::ctlPassword;
		setAccess(ctlAccess::write);
		return true;
	}
	unsigned ctlPassword::getANSITextSize()
	{
		return _password_pack.ansiLength();
	}
	unsigned ctlPassword::getText(char* lpszText, unsigned bufferLen)
	{
		return _password_pack.get(lpszText, bufferLen);
	}
	unsigned ctlPassword::getText(std::wstring::pointer lpszText, unsigned bufferLen)
	{
		return _password_pack.get(lpszText, bufferLen);
	}
	std::string ctlPassword::getText()
	{
		return _password_pack.getstr();
	}
	std::wstring ctlPassword::getWideText()
	{
		return _password_pack.getwidestr();
	}
	ctlPassword::_exactPos ctlPassword::_insert_text(_exactPos pos, const _ctlInterior::textpack& text)
	{
		if(!accessWrite()) return pos;
		std::wstring wstr(text.length(), L'\x25cf');
		_exactPos result = ctlSingleEdit::_insert_text(pos, 
			*_ctlInterior::createCompatibleTextPack(&wstr));
		_password_pack.stdwstr().insert(_password_pack.stdwstr().begin() + pos, 
			text.stdwstr().begin(), text.stdwstr().end());
		return result;
	}
	void ctlPassword::_remove_selected()
	{
		if(!accessWrite()) return;
		_exactPos begin = ctlMin(_edit_caret_pos_begin, _edit_caret_pos_end), 
			end = ctlMax(_edit_caret_pos_begin, _edit_caret_pos_end);
		_password_pack.stdwstr().erase(
			_password_pack.stdwstr().begin() + begin, _password_pack.stdwstr().begin() + end);
		ctlSingleEdit::_remove_selected();
	}
	void ctlPassword::_key_event_(ctlKeyEvent* ke)
	{
		if(ke->eventType == ctlKeyEventType::down
			&& (GetKeyState(VK_CONTROL) & 0xff00)
			&& (ke->charInfo.virtualKey == 'Z' || ke->charInfo.virtualKey == 'V'))
			ctlRoot::_key_event_(ke);
		else ctlSingleEdit::_key_event_(ke);
	}
}